<template>
    <div style='text-shadow: none'>
        <el-dialog
            :append-to-body="true"
            title='提示'
            :visible.sync='linkDialogVisible'
            width='30%'
            :before-close='handleLinkClose'>
            <span>按任意按键连接手柄</span>
            <span slot='footer' class='dialog-footer'>
                <el-button @click="handleLinkDialog">跳过连接</el-button>
            </span>
        </el-dialog>
        <el-dialog
            :append-to-body="true"
            title='使用指南'
            :visible.sync='guideDialogVisible'
            width='80%'
            :before-close='handleGuideClose'>
            <span>（占位）</span>
            <span slot='footer' class='dialog-footer'>
                <el-button @click="guideDialogVisible = false">Ⓑ 取 消</el-button>
                <el-button type='primary' @click='guideDialogVisible = false;'>Ⓐ 确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'OperatorGuide',
    data() {
        return {
            valueL: false,
            value2: true,
            value3: true,
            valueR: false,
            guideDialogVisible: false,
            linkDialogVisible: true,
            flag : false
        };
    },
    created() {
        var _this = this;
        var restoredSession = JSON.parse(sessionStorage.getItem('gamepadInfo'));
        if (restoredSession === 'connected') {
            _this.startgamepad(); // 启动手柄
            _this.linkDialogVisible = false;
            _this.$message.success('手柄已连接');
            if (_this.flag === false) {
                _this.guideDialogVisible = true;
                _this.flag = true;
            }
        }
        // 监听游戏手柄
        window.addEventListener('gamepadconnected', function(e) {
            var gp = navigator.getGamepads()[e.gamepad.index];
            sessionStorage.setItem('gamepadInfo', JSON.stringify("connected"))
            _this.startgamepad(); // 启动手柄
            _this.linkDialogVisible = false;
            _this.$message.success('手柄已连接');
            if (_this.flag === false) {
                _this.guideDialogVisible = true;
                _this.flag = true;
            }
        });
        // 监听游戏手柄拔出
        window.addEventListener('gamepaddisconnected', function(e) {
            clearInterval(_this.interval); // 停止获取手柄数据
            sessionStorage.setItem('gamepadInfo', JSON.stringify("disconnected"))
        });
    },
    methods: {
        handleGuideDialog(done) {
            if (this.guideDialogVisible === false) {
                this.guideDialogVisible = true;
            }
            else {
                this.guideDialogVisible = false;
            }
        },
        handleGuideClose(done) {
            if (this.guideDialogVisible === true) {
                this.guideDialogVisible = false;
            }
        },
        handleLinkDialog() {
            this.linkDialogVisible = false;
            this.$message.warning('手柄未连接');
            // this.guideDialogVisible = true;
            // this.flag = true;
        },
        handleLinkClose(done) {
            this.$confirm('确认跳过连接？')
                .then(_ => {
                    done();
                    this.$message.warning('手柄未连接');
                    // this.guideDialogVisible = true;
                    // this.flag = true;
                })
                .catch(_ => {});
        },
        forward: function() {
            // 从接口获取数据并添加到数组
            this.$axios.get(this.GLOBAL.serverIp + '/api/forward/').then((res) => {
                if (res.data.status !== 200) {
                    this.$message.error('连接错误，前进指令未传达');
                } else {
                    this.$message.success('前进指令已传达');
                }
            }).catch((error)=> {
                this.$message.error('无法连接到鱼体，前进指令未传达');
            });
        },
        backward: function() {
            // 从接口获取数据并添加到数组
            this.$axios.get(this.GLOBAL.serverIp + '/api/backward/').then((res) => {
                if (res.data.status !== 200) {
                    this.$message.error('连接错误，后退指令未传达');
                } else {
                    this.$message.success('后退指令已传达');
                }
            }).catch((error)=> {
                this.$message.error('无法连接到鱼体，后退指令未传达');
            });
        },
        upward: function() {
            // 从接口获取数据并添加到数组
            this.$axios.get(this.GLOBAL.serverIp + '/api/upward/').then((res) => {
                if (res.data.status !== 200) {
                    this.$message.error('连接错误，上浮指令未传达');
                } else {
                    this.$message.success('上浮指令已传达');
                }
            }).catch((error)=> {
                this.$message.error('无法连接到鱼体，上浮指令未传达');
            });
        },
        downward: function() {
            // 从接口获取数据并添加到数组
            this.$axios.get(this.GLOBAL.serverIp + '/api/downward/').then((res) => {
                if (res.data.status !== 200) {
                    this.$message.error('连接错误，下潜指令未传达');
                } else {
                    this.$message.success('下潜指令已传达');
                }
            }).catch((error)=> {
                this.$message.error('无法连接到鱼体，下潜指令未传达');
            });
        },
        stop: function() {
            // 从接口获取数据并添加到数组
            this.$axios.get(this.GLOBAL.serverIp + '/api/stop/').then((res) => {
                if (res.data.status !== 200) {
                    this.$message.error('连接错误，停止指令未传达');
                } else {
                    this.$message.success('停止指令已传达');
                }
            }).catch((error)=> {
                this.$message.error('无法连接到鱼体，停止指令未传达');
            });
        },
        turnLeft: function() {
            // 从接口获取数据并添加到数组
            this.$axios.get(this.GLOBAL.serverIp + '/api/turnLeft/').then((res) => {
                if (res.data.status !== 200) {
                    this.$message.error('连接错误，左转指令未传达');
                } else {
                    this.$message.success('左转指令已传达');
                }
            }).catch((error)=> {
                this.$message.error('无法连接到鱼体，左转指令未传达');
            });
        },
        turnRight: function() {
            this.$message.info('右转指令发送中：')
            // 从接口获取数据并添加到数组
            this.$axios.get(this.GLOBAL.serverIp + '/api/turnRight/').then((res) => {
                if (res.data.status !== 200) {
                    this.$message.error('连接错误，右转指令未传达');
                } else {
                    this.$message.success('右转指令已传达');
                }
            }).catch((error)=> {
                this.$message.error('无法连接到鱼体，右转指令未传达');
            });
        },
        dispose: function() {
            // 从接口获取数据并添加到数组
            this.$axios.get(this.GLOBAL.serverIp + '/api/dispose/').then((res) => {
                if (res.data.status !== 200) {
                    this.$message.error('连接错误，抛载指令未传达');
                } else {
                    this.$message.success('抛载指令已传达');
                }
            }).catch((error)=> {
                this.$message.error('无法连接到鱼体，抛载指令未传达');
            });
        },
        leftWingCtrl: function() {
            let v1 = this.valueL;
            if (v1) {
                this.$axios.get(this.GLOBAL.serverIp + '/api/leftWingOpen/').then((res) => {
                    if (res.data.status !== 200) {
                        this.$message.error('连接错误，左机侧翼开启指令未传达');
                    } else {
                        this.$message.success('左机侧翼开启指令已传达');
                    }
                }).catch((error)=> {
                    this.$message.error('无法连接到鱼体，左机侧翼开启指令未传达');
                    this.valueL = 1;
                });
            } else {
                this.$axios.get(this.GLOBAL.serverIp + '/api/leftWingClose/').then((res) => {
                    if (res.data.status !== 200) {
                        this.$message.error('连接错误，左机侧翼关闭指令未传达');
                    } else {
                        this.$message.success('左机侧翼关闭指令已传达');
                    }
                }).catch((error)=> {
                    this.$message.error('无法连接到鱼体，左机侧翼关闭指令未传达');
                    this.valueL = 0;
                });
            }
            this.valueL = v1;
        },
        rightWingCtrl: function() {
            //console.log(this.valueR)
            let v1 = this.valueR;
            if (v1) {
                this.$axios.get(this.GLOBAL.serverIp + '/api/rightWingOpen/').then((res) => {
                    if (res.data.status !== 200) {
                        this.$message.error('连接错误，右机侧翼开启指令未传达');
                    } else {
                        this.$message.success('右机侧翼开启指令已传达');
                    }
                }).catch((error)=> {
                    this.$message.error('无法连接到鱼体，右机侧翼开启指令未传达');
                    this.valueR = 0;
                });
            } else {
                this.$axios.get(this.GLOBAL.serverIp + '/api/rightWingClose/').then((res) => {
                    if (res.data.status !== 200) {
                        this.$message.error('连接错误，右机侧翼关闭指令未传达');
                    } else {
                        this.$message.success('右机侧翼关闭指令已传达');
                    }
                }).catch((error)=> {
                    this.$message.error('无法连接到鱼体，右机侧翼关闭指令未传达');
                    this.valueR = 1;
                });
            }
            this.valueR = v1;
        },
        // 启动手柄
        startgamepad() {
            var _this = this;
            // 每200ms 获取一次手柄数据，查看是否按下手柄按键
            this.interval = setInterval(function() {
                var gamepad = navigator.getGamepads()[0];
                _this.remoteSensing(gamepad.axes);
                _this.pressKey(gamepad.buttons);
            }, 200);
        },
        // 手柄遥感
        remoteSensing(arr) {
            let eps = 2e-1; //降低敏感度以提升兼容
            let diff = 1e-1;
            if (Math.abs(arr[0]) <= eps &&
                Math.abs(arr[1]) <= eps &&
                Math.abs(arr[2]) <= eps &&
                Math.abs(arr[0]) <= eps) {
                return;
            }
            // console.log(arr);
            //left remote
            if (Math.abs(arr[0]) > eps || Math.abs(arr[1]) > eps) {
                if (Math.abs(arr[0] - arr[1]) < diff) {
                    if (arr[0] > 0) {
                        this.turnRight();
                    } else {
                        this.turnLeft();
                    }
                    if (arr[1] > 0) {
                        this.backward();
                    } else {
                        this.forward();
                    }
                } else if (Math.abs(arr[0]) > Math.abs(arr[1])) {
                    if (arr[0] > 0) {
                        this.turnRight();
                    } else {
                        this.turnLeft();
                    }
                } else {
                    if (arr[1] > 0) {
                        this.backward();
                    } else {
                        this.forward();
                    }
                }
            }
            //right remote, left empty for now
            if (Math.abs(arr[2]) > eps || Math.abs(arr[3]) > diff) {
            }
        },
        // 手柄按键
        pressKey(arr) {
            // console.log(arr);
            for (let i = 0; i < arr.length; i++) {
                if (arr[i].value == 1) {
                    console.log(i);
                    // 根据个人情况判断；不同手柄值不同。
                    if (i == 0) {
                        console.log('A');
                        this.handleGuideClose();
                    }
                    if (i == 1) {
                        console.log('B');
                        this.handleGuideClose();
                    }
                    if (i == 2) {
                        console.log('X');
                    }
                    if (i == 3) {
                        console.log('Y');
                    }

                    if (i == 4) {
                        console.log('左手1');
                    }
                    if (i == 5) {
                        console.log('右手1');
                    }
                    if (i == 6) {
                        console.log('左手2');
                        this.stop();
                    }
                    if (i == 7) {
                        console.log('右手2');
                        this.stop();
                    }

                    if (i == 8) {
                        console.log('BACK');
                    }
                    if (i == 9) {
                        console.log('START');
                        this.handleGuideDialog();
                        console.log(this.guideDialogVisible);
                    }

                    if (i == 10) {
                        console.log('左遥感按下');
                        this.dispose();
                    }
                    if (i == 11) {
                        console.log('右遥感按下');
                        this.dispose();
                    }

                    if (i == 12) {
                        console.log('上');
                        this.upward();
                    }
                    if (i == 13) {
                        console.log('下');
                        this.downward();
                    }
                    if (i == 14) {
                        console.log('左');
                        this.valueL = this.valueL !== true;
                        this.leftWingCtrl();
                    }
                    if (i == 15) {
                        console.log('右');
                        this.valueR = this.valueR !== true;
                        this.rightWingCtrl();
                    }
                }
            }
        }
    }
};
</script>

<style scoped>
.el-row {
    margin-top: 10px;
    margin-bottom: 10px;
}

.button1 {
    height: 100px;
}

.button2 {
    height: 65px;
}

.button3 {
    width: 85px;
    height: 65px;
}
</style>
